#!/bin/bash

DOCKER_OHOS_TAG="1"

export GREEN="\e[32m\e[1m"
export RED="\e[31m\e[1m"
export YELLOW="\e[33m\e[1m"
export CLEAR="\e[0m"

function tmp_dir_help(){
    echo -e "${RED}How to fix incorrect tmp home dir${CLEAR}:
    1. make sure you don't have any running containers, check with \`docker ps | grep $USER\q and stop/kill them with \`docker stop\` and \`docker rm\`
    2. make sure there are no other processes working with the dir: \`lsof ${my_tmp_home}\` or stop them
    3. unmount and remove temp files:
       a) \`sudo umount ${my_tmp_home}/project\`
       b) \`rm -rf ${my_tmp_home}\`
       "
    clean
    exit 1
}

function clean(){
    echo -e "${RED}CLEAN${CLEAR}"
    cd "${my_tmp_home}"
#    sudo mount -t overlay overlay -o lowerdir=/home"${USER}",upperdir=./upper,workdir=./workdir project
#    sudo umount "${my_tmp_home}/project"
    rm -rf "${my_tmp_home}"
}

echo -e "${GREEN}$0 ${DOCKER_OHOS_TAG}${CLEAR} starts a container to help you with bla bla bla
"

my_ip=$(ip a | grep -v tun0 | grep -Po '(?<=inet )10\.[^/]+')
docker_ip=$(ip a | grep docker0 -A2 | grep -Po '(?<=inet )[^/]+')

if [[ $(echo "${my_ip}" | wc -l) -ne 1 ]]; then
    echo "Can't find your IP. Probably, you have two interfaces?"
    echo "Check \`ip a | grep 10\\\\\.\` gives you only 1 line"
fi

my_uid=$(id -u)
my_gid=$(id -g)
domain_gid=100513
my_port=""
my_name="docker-ohos-${USER}"
my_tmp_home="/tmp/${my_name}"

echo -e "bla bla help"

echo -e "Making a temp home dir ${my_tmp_home} ..."
#mkdir "${my_tmp_home}" || tmp_dir_help
#cd "${my_tmp_home}" || tmp_dir_help
#mkdir {upper,workdir,project} || tmp_dir_help
#sudo mount -t overlay overlay -o lowerdir=/home/"${USER}",upperdir=./upper,workdir=./workdir project || tmp_dir_help
#cd - || tmp_dir_help


docker run --rm -it -v "${PWD}":/opt/docker -v "${HOME}:/home/${USER}" \
           -v "/data/shared/ohos_mirror:/data/shared/ohos_mirror" -v "/data/shared/openharmony_prebuilts:/data/shared/openharmony_prebuilts" \
           -v "/data/shared/CCACHE:/data/shared/CCACHE" \
           -e username="${USER}" -e user_id="${my_uid}" -e user_gid="${my_gid}" --name "${my_name}" \
           --pull always tsnnlx12bs02:8082/ohos_build:"${DOCKER_OHOS_TAG}"
           #nexus.cn.bz-openlab.ru:10443/repository/docker-group/v2/huawei/ohos-build/manifests/22.04
#docker run --rm -it -v "${PWD}":/opt/docker -v "${my_tmp_home}/project:/home/${USER}" \
#           -v /data/shared/ohos_mirror:/data/shared/ohos_mirror -v /data/shared/openharmony_prebuilts:/data/shared/openharmony_prebuilts \
#           -e username="${USER}" -e user_id="${my_uid}" -e user_gid="${my_gid}" --name "${my_name}" \
#           swr.cn-south-1.myhuaweicloud.com/openharmony-docker/docker_oh_standard:3.2

#sudo umount "${my_tmp_home}/project" || tmp_dir_help

# workaround for problem with special files in workdir - user cannot remove it
#clean

